package lcrypto

import (
	"encoding/base64"

	"github.com/tjfoc/gmsm/sm4"
)

func NewSM4(key string) *SM4 {
	return &SM4{key: []byte(key)}
}

type SM4 struct {
	key []byte // 长度必须是16
}

func (sm *SM4) Name() string {
	return "sm4"
}

func (sm *SM4) Encrypt(plain []byte) (cipher []byte, err error) {
	buf, err := sm4.Sm4Cbc(sm.key, plain, true)
	if err != nil {
		return cipher, err
	}
	encoded := base64.StdEncoding.EncodeToString(buf)
	return []byte(encoded), err

}

func (sm *SM4) Decrypt(cipher []byte) (plain []byte, err error) {
	decoded, err := base64.StdEncoding.DecodeString(string(cipher))
	if err != nil {
		return plain, err
	}
	return sm4.Sm4Cbc(sm.key, decoded, false)
}
